﻿#include "jfCameraItem.h"



int CALLBACK pMsgCallback(XSDK_HANDLE hObject, int nMsgId, int nParam1, int nParam2, int nParam3,
    const char* szString, void* pObject, int64 lParam, int nSeq, void* pUserData, void* pMsg)
{
    // 13001 局域网下搜索设备 param1: 设备数量
    // 12001 登录设备结果 param1: >=0 登录成功 <0对应错误码
    // 12106 ESXSDK_DEV_SNAP 设备通道抓图 [param1]结果值 [param2]图片数据长度 [pObject]Jpg格式图片数据


    switch (nMsgId)
    {

    case 12001:
        if(nParam1 >= 0)    {
            QMLSignal::I().emitCameraConnect(true);
        }
        else{
            QMLSignal::I().emitCameraConnect(false);
        }
        break;

    case ESXSDK_DEV_SNAP: {

        QImage image;
        QMLSignal::I().emitRefreshJFCamera(nParam2, pObject);

    }
        break;
    default:
        break;
    }
    return 0;
}



JFCameraItem::JFCameraItem(QString name, QString ip, int port, QString usrName, QString pswd)
    : _cameraName(name), _cameraIp(ip), _cameraPort(port), _cameraUsrName(usrName), _cameraPassword(pswd)
{
    const char* sInit = "{\"LogLevel\":0,\"TempPath\":\"\",\"ConfigPath\":\"\",\"PlatUUID\":\"\",\"PlatAppKey\":\"\",\"PlatAppSecret\":\"\",\"PlatMovedCard\":0,\"ServerIP\":\"\",\"ServerPort\":34567}";
    XCloudSDK_Init(sInit);

    lUserID = XCloudSDK_RegisterCallback((PXSDK_MessageCallBack)(pMsgCallback), NULL);

    connect(&QMLSignal::I(), SIGNAL(refreshJFCamera(int, void*)), this, SLOT(updateCameraImage(int, void*)));
}

void JFCameraItem::run(){
    if(!isConnected){
        qDebug() << "相机" << _cameraName << "未连接，线程启动失败";
        _keepRun = false;
        return;
    }else{
        qDebug() << "相机" << _cameraName << "的线程开始run";
    }
    while(1){
        if(!_keepRun){
            qDebug() << "相机"<< _cameraName << "线程已终止";
            return;
        }
        captureImage();
#ifdef Q_OS_WINDOWS
        Sleep(100);
#endif
#ifdef Q_OS_LINUX
//        sleep(40);
#endif
    }
}
void JFCameraItem::start(){

    startStopMutex.lock();
    _keepRun = true;
    QThread::start();
    int whileNum = 0;
    while(!QThread::isRunning()){
        Sleep(10);
        if(whileNum > 200){
            __LOG_ERROR("!!WhileCannotStop");
            qDebug() << "错误：CameraStart的while进入死循环，已强行终止";
            break;
        }
    }
    startStopMutex.unlock();
}
void JFCameraItem::stop(){
    startStopMutex.lock();
    _keepRun = false;
    int whileNum = 0;
    while(QThread::isRunning()){
        Sleep(10);
        if(whileNum > 200){
            __LOG_ERROR("!!WhileCannotStop");
            qDebug() << "错误：CameraStart的while进入死循环，已强行终止";
            break;
        }
    }
    startStopMutex.unlock();
}


void JFCameraItem::connectCamera(){

    XCloudSDK_Device_SetLocalUserNameAndPwd((_cameraIp+":"+QString::number(_cameraPort)).toLatin1(), _cameraUsrName.toLatin1(), _cameraPassword.toLatin1());
    // 登录设备
    XCloudSDK_Device_DevLogin(lUserID, (_cameraIp+":"+QString::number(_cameraPort)).toLatin1(), 0);


    isConnected = true;
}

void JFCameraItem::logout(){

}


/** @brief 捕获图像 */
void JFCameraItem::captureImage(){

    if(!isConnected)    return;
    if(!_provider)      return;

    XCloudSDK_Device_DevSnap(lUserID, (_cameraIp+":"+QString::number(_cameraPort)).toLatin1(), 0);

}

void JFCameraItem::setProvider(QSharedPointer<CameraImageProvider> provider){
    _provider = provider;
}

void JFCameraItem::clearProvider(){
    _provider = nullptr;
}

void JFCameraItem::updateCameraImage(int nParam2, void* pObject){


    _provider->lock();
    bool res = _provider->pm->loadFromData((uchar*)pObject, nParam2);
//    bool res = _provider->pm->save("./" + QTime::currentTime().toString() + ".jpg");
    _provider->unlock();
    emit sigRefresh(_cameraName);
}
